<?php

namespace App\Http\Controllers\Admin\SuperAdmin;

use App\Exceptions\LoginException;
use App\Services\Admin\SuperAdmin\User\LoginService;
use Exception;
use Illuminate\Http\JsonResponse;

class LoginController extends BaseSuperAdminController
{

    protected LoginService $loginService;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->loginService = loadService('Admin\SuperAdmin\User\LoginService');
        parent::__construct();
    }

    /**
     * 获取验证码
     *
     * @return JsonResponse
     */
    public function captcha(): JsonResponse
    {
        $result = $this->loginService->captcha();
        return outputJsonResult($result);
    }

    /**
     * 登录
     *
     * @return JsonResponse
     * @throws LoginException
     */
    public function login(): JsonResponse
    {
        $rule = [
            'username' => 'required|string|min:1',
            'password' => 'required|string|min:1',
            'captcha' => 'required|string|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $result = $this->loginService->login($this->params);

        return outputJsonResult($result);
    }

    /**
     * 退出登录
     *
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        $this->loginService->logout();
        return outputJsonResult();
    }
}
